package com.beeweeb.services.tps.mbean;

import java.security.PrivilegedAction;
import java.security.AccessController;

class ThreadPoolSchedulerClassLoader {

    private static class SchedulerClassLoaderAction implements PrivilegedAction {

        static PrivilegedAction ACTION = new SchedulerClassLoaderAction();

        public Object run() {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            return loader;
        }
    }

    private static class GetClassLoaderAction implements PrivilegedAction {

        Class c;

        GetClassLoaderAction(Class c) {
            this.c = c;
        }

        public Object run() {
            ClassLoader loader = c.getClassLoader();
            c = null;
            return loader;
        }
    }

    private static class SetTCLAction implements PrivilegedAction {

        ClassLoader loader;

        SetTCLAction(ClassLoader loader) {
            this.loader = loader;
        }

        public Object run() {
            Thread.currentThread().setContextClassLoader(loader);
            loader = null;
            return null;
        }
    }

    static ClassLoader getContextClassLoader() {
        ClassLoader loader = (ClassLoader) AccessController.doPrivileged(SchedulerClassLoaderAction.ACTION);
        return loader;
    }

    static ClassLoader getClassLoader(Class c) {
        GetClassLoaderAction action = new GetClassLoaderAction(c);
        ClassLoader loader = (ClassLoader) AccessController.doPrivileged(action);
        return loader;
    }

    static void setContextClassLoader(ClassLoader loader) {
        PrivilegedAction action = new SetTCLAction(loader);
        AccessController.doPrivileged(action);
    }
}
